{% extends 'base.html' %}

{% block title %}系统设置 | Tiny QA{% endblock %}

{% block content %}
<div class="container mt-5">
    <h2 class="mb-4">
        <i class="bi bi-gear-fill me-2"></i>系统设置
    </h2>
    
    <!-- 当前配置信息 -->
    <div class="alert alert-info mb-4">
        <h6><i class="bi bi-info-circle me-2"></i>当前配置</h6>
        <div class="row">
            <div class="col-md-6">
                <strong>文档目录:</strong> <span id="current-docs-path">加载中...</span>
            </div>
            <div class="col-md-3">
                <strong>分块大小:</strong> <span id="current-chunk-size">加载中...</span>
            </div>
            <div class="col-md-3">
                <strong>分块重叠:</strong> <span id="current-chunk-overlap">加载中...</span>
            </div>
        </div>
    </div>
    
    <form id="settings-form" class="mb-3">
        <!-- 文档目录配置 -->
        <div class="mb-4">
            <h5 class="text-primary mb-3">
                <i class="bi bi-folder-fill me-2"></i>文档目录配置
            </h5>
            <div class="alert alert-warning">
                <i class="bi bi-exclamation-triangle me-2"></i>
                <strong>重要提示：</strong>修改文档目录后，需要重新扫描和处理文档。
            </div>
            
            <div class="mb-3">
                <label for="documents_path" class="form-label fw-bold">文档目录路径</label>
                <div class="input-group">
                    <input type="text" class="form-control" id="documents_path" 
                           name="documents_path" required 
                           placeholder="请输入本地文档目录的完整路径">
                    <button class="btn btn-outline-secondary" type="button" id="help-btn">
                        <i class="bi bi-question-circle"></i> 帮助
                    </button>
                    <button class="btn btn-outline-primary" type="button" id="validate-btn">
                        <i class="bi bi-check-circle"></i> 验证
                    </button>
                </div>
                <div class="form-text">
                    <strong>支持的文档格式：</strong>PDF (.pdf), Word (.docx), Excel (.xlsx), 文本 (.txt), Markdown (.md)
                </div>
                <div class="alert alert-info mt-2">
                    <i class="bi bi-info-circle me-2"></i>
                    <strong>Docker环境说明：</strong>请输入您本地主机的文档目录路径，系统将自动建立卷映射关系。
                </div>
            </div>
            
            <!-- 路径验证结果 -->
            <div id="path-validation" class="d-none">
                <div id="validation-result"></div>
                <div id="file-count" class="mt-2"></div>
            </div>
        </div>

        <!-- 分块配置 -->
        <div class="mb-4">
            <h5 class="text-primary mb-3">
                <i class="bi bi-puzzle-fill me-2"></i>分块配置
            </h5>
            <div class="row">
                <div class="col-md-6">
                    <div class="mb-3">
                        <label for="chunk_size" class="form-label">分块大小 (字符数)</label>
                        <input type="number" class="form-control" id="chunk_size" 
                               name="chunk_size" min="100" max="5000" required>
                        <div class="form-text">建议范围: 500-2000字符</div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="mb-3">
                        <label for="chunk_overlap" class="form-label">分块重叠 (字符数)</label>
                        <input type="number" class="form-control" id="chunk_overlap" 
                               name="chunk_overlap" min="0" max="1000" required>
                        <div class="form-text">建议范围: 50-500字符</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- AI模型配置 -->
        <div class="mb-4">
            <h5 class="text-primary mb-3">
                <i class="bi bi-robot me-2"></i>AI模型配置
            </h5>
            <div class="row">
                <div class="col-md-6">
                    <div class="mb-3">
                        <label for="current_model" class="form-label">当前模型</label>
                        <select class="form-select" id="current_model" name="current_model" required>
                            <option value="">加载中...</option>
                        </select>
                        <div class="form-text">选择用于问答的AI模型</div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="mb-3">
                        <label class="form-label">模型状态</label>
                        <div class="d-flex align-items-center">
                            <div id="model-status" class="form-control-plaintext flex-grow-1">
                                <i class="bi bi-arrow-clockwise spin"></i> 检查中...
                            </div>
                            <button type="button" class="btn btn-outline-secondary btn-sm ms-2" id="refresh-models-btn">
                                <i class="bi bi-arrow-clockwise"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 问答配置 -->
        <div class="mb-4">
            <h5 class="text-primary mb-3">
                <i class="bi bi-chat-dots me-2"></i>问答配置
            </h5>
            <div class="row">
                <div class="col-md-6">
                    <div class="mb-3">
                        <label for="max_sources" class="form-label">最大参考来源数量</label>
                        <input type="number" class="form-control" id="max_sources" 
                               name="max_sources" min="1" max="10" required>
                        <div class="form-text">建议范围: 3-8个来源</div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="mb-3">
                        <label for="source_content_length" class="form-label">来源内容显示长度</label>
                        <input type="number" class="form-control" id="source_content_length" 
                               name="source_content_length" min="100" max="500" required>
                        <div class="form-text">建议范围: 150-300字符</div>
                    </div>
                </div>
            </div>
        </div>

        <div class="d-flex gap-2">
            <button type="submit" class="btn btn-primary">
                <i class="bi bi-save me-2"></i>保存设置
            </button>
            <button type="button" class="btn btn-outline-secondary" id="reset-btn">
                <i class="bi bi-arrow-clockwise me-2"></i>重置为默认值
            </button>
        </div>
    </form>
    
    <div id="settings-msg" class="alert d-none"></div>
</div>

<script>
// 显示帮助信息
function showHelp() {
    Swal.fire({
        title: '文档目录配置帮助',
        html: `
            <div class="text-start">
                <h6>📁 路径格式示例：</h6>
                <ul class="text-start">
                    <li><strong>Windows:</strong> C:\\Users\\YourName\\Documents</li>
                    <li><strong>macOS:</strong> /Users/YourName/Documents</li>
                    <li><strong>Linux:</strong> /home/YourName/documents</li>
                </ul>
                <hr>
                <h6>🔧 Docker环境说明：</h6>
                <p>在Docker环境中，您需要输入本地主机的文档目录路径。系统会自动建立卷映射关系，将您的本地目录挂载到容器内部。</p>
                <hr>
                <h6>📋 支持的文档格式：</h6>
                <ul class="text-start">
                    <li>PDF (.pdf)</li>
                    <li>Word (.docx)</li>
                    <li>Excel (.xlsx)</li>
                    <li>文本 (.txt)</li>
                    <li>Markdown (.md)</li>
                </ul>
            </div>
        `,
        icon: 'info',
        confirmButtonText: '明白了'
    });
}

// 路径验证
async function validatePath() {
    const path = document.getElementById('documents_path').value.trim();
    if (!path) {
        Swal.fire({
            icon: 'warning',
            title: '请输入路径',
            text: '请先输入文档目录路径'
        });
        return;
    }

    const validateBtn = document.getElementById('validate-btn');
    const originalText = validateBtn.innerHTML;
    validateBtn.disabled = true;
    validateBtn.innerHTML = '<i class="bi bi-arrow-clockwise spin"></i> 验证中...';

    try {
        const response = await fetch('/api/validate-path', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ path: path })
        });

        const data = await response.json();
        const validationDiv = document.getElementById('path-validation');
        const resultDiv = document.getElementById('validation-result');
        const fileCountDiv = document.getElementById('file-count');

        validationDiv.classList.remove('d-none');

        if (response.ok) {
            resultDiv.className = 'alert alert-success';
            resultDiv.innerHTML = `
                <i class="bi bi-check-circle me-2"></i>
                <strong>路径验证成功！</strong><br>
                发现 ${data.file_count} 个支持格式的文档文件
            `;
            
            if (data.file_count > 0) {
                fileCountDiv.innerHTML = `
                    <div class="small text-muted">
                        <strong>文件类型分布：</strong><br>
                        ${data.file_types.map(type => `${type.extension}: ${type.count}个`).join(', ')}
                    </div>
                `;
            }
        } else {
            resultDiv.className = 'alert alert-danger';
            resultDiv.innerHTML = `
                <i class="bi bi-x-circle me-2"></i>
                <strong>路径验证失败：</strong> ${data.error}
            `;
            fileCountDiv.innerHTML = '';
        }
    } catch (error) {
        const validationDiv = document.getElementById('path-validation');
        const resultDiv = document.getElementById('validation-result');
        
        validationDiv.classList.remove('d-none');
        resultDiv.className = 'alert alert-danger';
        resultDiv.innerHTML = `
            <i class="bi bi-x-circle me-2"></i>
            <strong>验证失败：</strong> ${error.message}
        `;
    } finally {
        validateBtn.disabled = false;
        validateBtn.innerHTML = originalText;
    }
}

// 加载当前设置
async function loadSettings() {
    try {
        const resp = await fetch('/api/config');
        const data = await resp.json();
        
        // 设置表单值
        document.getElementById('documents_path').value = data.documents_path || '';
        document.getElementById('chunk_size').value = data.chunk_size || 1000;
        document.getElementById('chunk_overlap').value = data.chunk_overlap || 200;
        document.getElementById('max_sources').value = data.max_sources || 5;
        document.getElementById('source_content_length').value = data.source_content_length || 200;
        
        // 显示当前配置
        document.getElementById('current-docs-path').textContent = data.documents_path || '未配置';
        document.getElementById('current-chunk-size').textContent = (data.chunk_size || 1000) + ' 字符';
        document.getElementById('current-chunk-overlap').textContent = (data.chunk_overlap || 200) + ' 字符';
        
        // 加载模型列表
        await loadModels();
        
    } catch (err) {
        document.getElementById('settings-msg').className = 'alert alert-danger';
        document.getElementById('settings-msg').textContent = '加载设置失败: ' + err.message;
        document.getElementById('settings-msg').classList.remove('d-none');
    }
}

// 加载模型列表
async function loadModels() {
    try {
        const resp = await fetch('/api/models');
        const data = await resp.json();
        
        const modelSelect = document.getElementById('current_model');
        const modelStatus = document.getElementById('model-status');
        
        if (resp.ok && data.models) {
            // 清空选项
            modelSelect.innerHTML = '';
            
            // 添加模型选项
            data.models.forEach(model => {
                const option = document.createElement('option');
                option.value = model.name;
                option.textContent = `${model.name} (${model.size || '未知大小'})`;
                if (model.name === data.current_model) {
                    option.selected = true;
                }
                modelSelect.appendChild(option);
            });
            
            // 记录原始模型
            modelSelect.setAttribute('data-original-model', data.current_model);
            
            // 更新模型状态
            modelStatus.innerHTML = `
                <i class="bi bi-check-circle text-success"></i> 
                已连接，发现 ${data.models.length} 个模型
            `;
        } else {
            modelSelect.innerHTML = '<option value="">加载失败</option>';
            modelStatus.innerHTML = `
                <i class="bi bi-x-circle text-danger"></i> 
                连接失败: ${data.error || '未知错误'}
            `;
        }
    } catch (err) {
        const modelSelect = document.getElementById('current_model');
        const modelStatus = document.getElementById('model-status');
        
        modelSelect.innerHTML = '<option value="">加载失败</option>';
        modelStatus.innerHTML = `
            <i class="bi bi-x-circle text-danger"></i> 
            连接失败: ${err.message}
        `;
    }
}

// 重置为默认值
function resetToDefaults() {
    Swal.fire({
        title: '确认重置',
        text: '确定要将所有设置重置为默认值吗？',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: '确定重置',
        cancelButtonText: '取消'
    }).then((result) => {
        if (result.isConfirmed) {
            document.getElementById('documents_path').value = '';
            document.getElementById('chunk_size').value = 1000;
            document.getElementById('chunk_overlap').value = 200;
            document.getElementById('max_sources').value = 5;
            document.getElementById('source_content_length').value = 200;
            
            // 重置模型选择
            const modelSelect = document.getElementById('current_model');
            if (modelSelect.options.length > 0) {
                modelSelect.selectedIndex = 0;
            }
            
            // 隐藏验证结果
            document.getElementById('path-validation').classList.add('d-none');
            
            Swal.fire({
                icon: 'success',
                title: '已重置',
                text: '设置已重置为默认值'
            });
        }
    });
}

// 保存设置
const form = document.getElementById('settings-form');
form.addEventListener('submit', async function(e) {
    e.preventDefault();
    
    const msg = document.getElementById('settings-msg');
    msg.classList.add('d-none');
    
    const documents_path = document.getElementById('documents_path').value.trim();
    const chunk_size = parseInt(document.getElementById('chunk_size').value);
    const chunk_overlap = parseInt(document.getElementById('chunk_overlap').value);
    const max_sources = parseInt(document.getElementById('max_sources').value);
    const source_content_length = parseInt(document.getElementById('source_content_length').value);
    const current_model = document.getElementById('current_model').value;
    
    if (!documents_path) {
        msg.className = 'alert alert-danger';
        msg.textContent = '文档目录路径不能为空';
        msg.classList.remove('d-none');
        return;
    }
    
    try {
        // 保存基本配置
        const resp = await fetch('/api/config', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                documents_path,
                chunk_size,
                chunk_overlap,
                max_sources,
                source_content_length
            })
        });
        
        // 保存模型配置
        if (current_model) {
            const modelResp = await fetch('/api/models', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ model_name: current_model })
            });
            
            if (!modelResp.ok) {
                const modelData = await modelResp.json();
                throw new Error(`模型更新失败: ${modelData.error}`);
            }
        }
        
        const data = await resp.json();
        
        if (resp.ok) {
            msg.className = 'alert alert-success';
            
            // 检查是否有模型更新
            const originalModel = document.getElementById('current_model').getAttribute('data-original-model');
            const hasModelChanged = originalModel && originalModel !== current_model;
            
            if (hasModelChanged) {
                // 模型更新提示
                msg.innerHTML = `
                    <i class="bi bi-check-circle me-2"></i>
                    <strong>模型更新成功！</strong><br>
                    当前模型已切换为: ${current_model}<br>
                    <small class="text-muted">新模型将在下次问答时生效</small>
                `;
            } else {
                // 文档配置更新提示
                msg.innerHTML = `
                    <i class="bi bi-check-circle me-2"></i>
                    <strong>设置保存成功！</strong><br>
                    文档目录已更新为: ${documents_path}<br>
                    <small class="text-muted">建议重新扫描文档以应用新配置</small>
                `;
            }
            
            msg.classList.remove('d-none');
            
            // 更新当前配置显示
            document.getElementById('current-docs-path').textContent = documents_path;
            document.getElementById('current-chunk-size').textContent = chunk_size + ' 字符';
            document.getElementById('current-chunk-overlap').textContent = chunk_overlap + ' 字符';
            
            // 更新原始模型记录
            document.getElementById('current_model').setAttribute('data-original-model', current_model);
        } else {
            throw new Error(data.error || '保存失败');
        }
    } catch (err) {
        msg.className = 'alert alert-danger';
        msg.textContent = '保存失败: ' + err.message;
        msg.classList.remove('d-none');
    }
});

// 事件监听
document.getElementById('help-btn').addEventListener('click', showHelp);
document.getElementById('validate-btn').addEventListener('click', validatePath);
document.getElementById('reset-btn').addEventListener('click', resetToDefaults);
document.getElementById('refresh-models-btn').addEventListener('click', loadModels);

// 页面加载时执行
window.onload = loadSettings;
</script>

<style>
.spin {
    animation: spin 1s linear infinite;
}

@keyframes spin {
    from { transform: rotate(0deg); }
    to { transform: rotate(360deg); }
}
</style>
{% endblock %} 